//年月日
#include <rclcpp/rclcpp.hpp>
// #include <std_msgs/msg/string.hpp>
#include <my_custom_msgs/msg/time_info.hpp>
#include <chrono>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <ctime>
#include <signal.h>

using namespace std::chrono_literals;

class TimePublisherNode : public rclcpp::Node
{
public:
    TimePublisherNode() : Node("time_publisher")
    {
        // 初始化发布器
        publisher_ = this->create_publisher<my_custom_msgs::msg::TimeInfo>("time_info", 10);
        
        // 获取开始时间
        start_time_ = std::chrono::steady_clock::now();
        
        // 设置定时器，每秒发布一次
        timer_ = this->create_wall_timer(
            1s, std::bind(&TimePublisherNode::timer_callback, this));
        
        // 处理Ctrl+C信号
        signal(SIGINT, signal_handler);
    }

private:
    void timer_callback()
    {
        // 获取当前时间
        auto current_time = std::chrono::system_clock::now();
        auto elapsed_time = std::chrono::steady_clock::now() - start_time_;
        
        // 获取当前时间的格式化字符串
        std::time_t now_c = std::chrono::system_clock::to_time_t(current_time);
        std::tm* tm_ptr = std::localtime(&now_c);
        std::ostringstream oss;
        oss << std::put_time(tm_ptr, "%Y年%m月%d日%H:%M:%S");
        std::string current_time_str = oss.str();

        // 将经过的时间转换为小时:分钟:秒格式
        int elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>(elapsed_time).count();
        int hours = elapsed_seconds / 3600;
        int minutes = (elapsed_seconds % 3600) / 60;
        int seconds = elapsed_seconds % 60;
        std::ostringstream elapsed_time_ss;
        elapsed_time_ss << hours << ":" << std::setw(2) << std::setfill('0') << minutes << ":" << std::setw(2) << std::setfill('0') << seconds;
        std::string elapsed_time_str = elapsed_time_ss.str();

        // 创建并发布消息
        my_custom_msgs::msg::TimeInfo time_info_msg;
        time_info_msg.current_time = current_time_str;  // 发布转换后的时间字符串
        time_info_msg.elapsed_time = elapsed_time_str;
        
        publisher_->publish(time_info_msg);
    }

    // 处理Ctrl+C信号
    static void signal_handler(int signum)
    {
        std::cout << "正在停止..." << std::endl;
        rclcpp::shutdown();
        exit(0);
    }

    rclcpp::Publisher<my_custom_msgs::msg::TimeInfo>::SharedPtr publisher_;
    rclcpp::TimerBase::SharedPtr timer_;
    std::chrono::steady_clock::time_point start_time_;
};

int main(int argc, char **argv)
{
    // 初始化ROS 2
    rclcpp::init(argc, argv);
    
    // 创建并运行节点
    rclcpp::spin(std::make_shared<TimePublisherNode>());
    
    // 清理资源
    rclcpp::shutdown();
    return 0;
}
